package com.example.terminalservice.security;

import cn.hutool.core.bean.BeanUtil;
import com.example.terminalservice.common.Result;
import com.example.terminalservice.mapper.MenuMapper;
import com.example.terminalservice.mapper.RoleMapper;
import com.example.terminalservice.pojo.Role;
import com.example.terminalservice.pojo.dto.UserDTO;
import com.example.terminalservice.service.MenuService;
import com.example.terminalservice.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 28142
 * @description LoginSuccessHandler
 * @date 2023/8/11 16:51
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuService menuService;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();

        String token = JwtUtils.createToken(securityUser.getUser());

        PrintWriter writer = response.getWriter();
        UserDTO userDTO = new UserDTO();
        BeanUtil.copyProperties(securityUser.getUser(), userDTO);
        userDTO.setToken(token);
        // 获取角色集合
        List<Role> roles = roleMapper.getRolesByUser(securityUser.getUser().getId());
        if (roles.size() > 0) {
            // 获取菜单集合
            userDTO.setMenus(menuService.getMenusByRoles(roles.stream().map(Role::getId).collect(Collectors.toList())));
        }
        System.out.println(userDTO);
        writer.write(objectMapper.writeValueAsString(Result.success("登录成功", userDTO)));
        writer.flush();
    }
}
